package com.wzu.rjgc_ks.controller;

import com.wzu.rjgc_ks.dao.LoginMapper;
import com.wzu.rjgc_ks.pojo.Admin;
import com.wzu.rjgc_ks.pojo.Company;
import com.wzu.rjgc_ks.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginAction {
    @Autowired
    LoginMapper loginMapper;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView Login(@RequestParam("userType")String userType, @RequestParam("username")String username, @RequestParam("password")String password, HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        switch (userType){
            case "学生":
                Student stu = loginMapper.stuLogin(username,password);
                System.out.println("1111111111111"+stu + "   " +username+"   "+password);
                if(stu != null){
                    request.getSession().setAttribute("users",stu);
                    request.getSession().setAttribute("stuId",stu.getStuId());
                    request.getSession().setAttribute("type",1);

                    mv.setViewName("redirect:/index");
                    return mv;
                }
                break;
            case "单位":
                Company com = loginMapper.comLogin(username,password);
                if(com != null){
                    request.getSession().setAttribute("users",com);
                    request.getSession().setAttribute("ComId",com.getComId());
                    request.getSession().setAttribute("type",2);
                    mv.setViewName("index");
                    return mv;
                }
                break;
            case "管理员":
                Admin admin = loginMapper.adminLogin(username,password);
                if(admin != null){
                    request.getSession().setAttribute("users",admin);
                    request.getSession().setAttribute("type",3);
                    mv.setViewName("index");
                    return mv;
                }
                break;
            }
        mv.setViewName("forward:/index");
        return mv;

    }

    @RequestMapping("/loginout")
    public  ModelAndView Loginout(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        HttpSession session = request.getSession();
        if(session != null){
            session.invalidate();
        }

        mv.setViewName("forward:/index");
        return mv;
    }
}
